# -*- coding: utf-8 -*-
"""
数据迁移工具 - 处理加密数据迁移
"""
import os
import sqlite3
from .path_manager import get_database_file, get_app_data_dir
from .simple_encryption import encryption_manager

class DataMigration:
    """数据迁移管理器"""
    
    def __init__(self):
        self.db_path = get_database_file()
        self.app_data_dir = get_app_data_dir()
    
    def migrate_encrypted_passwords(self):
        """迁移加密密码数据"""
        try:
            if not os.path.exists(self.db_path):
                print("数据库文件不存在，无需迁移")
                return True
            
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 检查是否有加密密码数据
            cursor.execute('''
                SELECT id, encrypted_password FROM db_connections 
                WHERE encrypted_password IS NOT NULL AND encrypted_password != ''
            ''')
            
            results = cursor.fetchall()
            if not results:
                print("没有需要迁移的加密密码数据")
                conn.close()
                return True
            
            print(f"找到 {len(results)} 条需要迁移的密码数据")
            
            # 尝试使用新的加密管理器解密旧数据
            migrated_count = 0
            failed_count = 0
            
            for connection_id, old_encrypted_password in results:
                try:
                    # 尝试解密旧密码
                    decrypted_password = encryption_manager.decrypt_password(old_encrypted_password)
                    
                    if decrypted_password:
                        # 使用新的加密管理器重新加密
                        new_encrypted_password = encryption_manager.encrypt_password(decrypted_password)
                        
                        if new_encrypted_password:
                            # 更新数据库
                            cursor.execute('''
                                UPDATE db_connections 
                                SET encrypted_password = ? 
                                WHERE id = ?
                            ''', (new_encrypted_password, connection_id))
                            
                            migrated_count += 1
                            print(f"✅ 迁移连接ID {connection_id} 的密码")
                        else:
                            print(f"❌ 重新加密失败: 连接ID {connection_id}")
                            failed_count += 1
                    else:
                        print(f"❌ 解密失败: 连接ID {connection_id}")
                        failed_count += 1
                        
                except Exception as e:
                    print(f"❌ 迁移连接ID {connection_id} 时出错: {e}")
                    failed_count += 1
            
            if migrated_count > 0:
                conn.commit()
                print(f"✅ 成功迁移 {migrated_count} 条密码数据")
            
            if failed_count > 0:
                print(f"⚠️ {failed_count} 条密码数据迁移失败，用户需要重新输入密码")
            
            conn.close()
            return True
            
        except Exception as e:
            print(f"数据迁移失败: {e}")
            return False
    
    def clear_old_encryption_key(self):
        """清理旧的加密密钥文件"""
        try:
            # 查找可能的旧密钥文件位置
            old_key_locations = [
                os.path.join(os.path.dirname(__file__), "..", "data", "encryption.key"),
                os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "encryption.key"),
            ]
            
            for key_file in old_key_locations:
                if os.path.exists(key_file):
                    try:
                        os.remove(key_file)
                        print(f"✅ 清理旧密钥文件: {key_file}")
                    except Exception as e:
                        print(f"⚠️ 无法清理旧密钥文件 {key_file}: {e}")
            
            return True
            
        except Exception as e:
            print(f"清理旧密钥文件失败: {e}")
            return False
    
    def backup_database(self):
        """备份数据库"""
        try:
            if not os.path.exists(self.db_path):
                return True
            
            backup_path = os.path.join(self.app_data_dir, "app_data_backup.db")
            
            # 复制数据库文件
            import shutil
            shutil.copy2(self.db_path, backup_path)
            print(f"✅ 数据库已备份到: {backup_path}")
            
            return True
            
        except Exception as e:
            print(f"数据库备份失败: {e}")
            return False
    
    def run_migration(self):
        """运行完整的数据迁移"""
        print("=== 开始数据迁移 ===")
        
        # 1. 备份数据库
        print("1. 备份数据库...")
        self.backup_database()
        
        # 2. 迁移加密密码
        print("2. 迁移加密密码...")
        self.migrate_encrypted_passwords()
        
        # 3. 清理旧密钥文件
        print("3. 清理旧密钥文件...")
        self.clear_old_encryption_key()
        
        print("=== 数据迁移完成 ===")
        return True

# 创建全局迁移实例
data_migration = DataMigration()
